package com.mrzhou.thread;

import com.mrzhou.DataUtil;

import java.util.Random;
import java.util.concurrent.ExecutionException;

/**
 * 两种方式创建线程的区别
 * @author qiang.zhou
 */
public class ThreadCreationCmp {

    public static void main(String[] args) {
        Thread thread;
        CountingTask task = new CountingTask();
        final int numberOfProcessors = Runtime.getRuntime().availableProcessors();
        for(int i = 0; i < 2 * numberOfProcessors; i++) {
            thread = new Thread(task);
            thread.start();
        }

        for(int i = 0; i < 2 * numberOfProcessors; i++) {
            thread = new CountThread();
            thread.start();
        }

    }
}

class Counter {
    private int count = 0;

    public void increment() {
        // 当前方法有线程安全问题， 实际count可能出现不符合预期的情况
        this.count++;
    }
    public int value() {
        return count++;
    }
}

class CountingTask implements Runnable {

    private Counter counter = new Counter();

    @Override
    public void run() {
        for(int i = 0; i < 100; i++) {
            randomSleep(81);
            counter.increment();
        }
        System.out.println("CountingTask-: " + counter.value());
    }

    public void randomSleep(long max) {
        try{
            Thread.sleep(DataUtil.randomLong(20, max));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class CountThread extends Thread {

    private Counter counter = new Counter();

    @Override
    public void run() {
        for(int i = 0; i < 100; i++) {
            randomSleep(81);
            counter.increment();
        }
        System.out.println("CountThread: " + counter.value());
    }

    public void randomSleep(long max) {
        try{
            Thread.sleep(DataUtil.randomLong(20, max));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}